﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;

public partial class Supervise_TraCompanyPS : System.Web.UI.Page, HZ.MBSM.BLL.TraDes
{
    public string _strEndDate, _strStartDate, _AreaId = "", _strUserType = "", _strAccountId_YY = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        BuildReport2.Enabled = false;
        BuildReport2.Visible = false;
        BuildReport1.Enabled = false;
        BuildReport1.Visible = false;
        if (HZ.MBSM.BLL.Login.CheckAssert(this.UseAccountType))
        {
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            if (_Account != null)
            {
                _AreaId = SysFun.ToTrim(_Account.AreaId);
                _strUserType = SysFun.ToTrim(_Account.Type);
                _strAccountId_YY = SysFun.ToTrim(_Account.AccountId);
            }
            if (_strUserType == "2")
            {
                //如果当前操作人是配送企业，那么就 初始化配送企业
                txtUserCode.Text = _Account.UserCode;
                txtUserCode.Enabled = false;
                txtAttorneyName.Text = _Account.DWName;
                txtAttorneyName.Enabled = false;
                 _AreaId = "530000";
            }
            if (_strUserType == "3")
            {
                //如果当前用户是医院，那么就把地区隐藏
                labArea.Visible = false;
                Label1.Visible = false;
            }
            else
            {
                BuildReport2.Enabled = true;
                BuildReport2.Visible = true;
                BuildReport1.Enabled = true;
                BuildReport1.Visible = true;
                //如果是监督机构或中介就根据其所在的地区来选择
                //如果是省一级的监督机构就可以看到整个云南省的信息,如果是某个市的监督机构就只能看到本市的信息
                System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
                string _strAreaNameForm, _strAreaIdForm;
                _strAreaNameForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaName"]));
                _strAreaIdForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaId"]));
                if (_strAreaNameForm != "" && _strAreaIdForm != "")
                {
                    strHtml.Append("<input type='text' name='txtAreaName' value ='" + _strAreaNameForm + "' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                    strHtml.Append("<input type='text' name='txtAreaId'  value ='" + _strAreaIdForm + "' style='display: none' />");
                }
                else
                {
                    strHtml.Append("<input type='text' name='txtAreaName' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                    strHtml.Append("<input type='text' name='txtAreaId' style='display: none' />");
                }
                if (_AreaId != "")
                {
                    strHtml.Append("<a href='javascript:AreaSelect(" + _AreaId + ")'>选择地区</a>");
                }
                labArea.Text = strHtml.ToString();
                labArea.Visible = true;
                Label1.Visible = true;
            }
            if (!IsPostBack)
            {
                //int Year, Month, Day;
                //Year = DateTime.Now.Year;
                //Month = DateTime.Now.Month - 1;
                //Day = DateTime.Now.Day;
                //txtStartDate.Text = Year.ToString() + "-" + Month.ToString() + "-01";

                //switch (Month)
                //{
                //    case 1:
                //    case 3:
                //    case 5:
                //    case 7:
                //    case 8:
                //    case 10:
                //    case 12:
                //        txtEndDate.Text = Year.ToString() + "-" + Month.ToString() + "-31";
                //        break;
                //    case 4:
                //    case 6:
                //    case 9:
                //    case 11:
                //        txtEndDate.Text = Year.ToString() + "-" + Month.ToString() + "-30";
                //        break;
                //    case 2:
                //        if (Year % 4 > 0)
                //        {
                //            txtEndDate.Text = Year.ToString() + "-" + Month.ToString() + "-28";
                //        }
                //        else
                //        {
                //            txtEndDate.Text = Year.ToString() + "-" + Month.ToString() + "-29";

                //        }
                //        break;
                //}

                ////初始化时间
                int Year, Month, Day, DMonth, Year1;
                Year = DateTime.Now.Year;
                Year1 = Year;
                DMonth = DateTime.Now.Month;
                Month = DMonth - 1;
                if (Month == 0)
                {
                    Year1 -= 1;
                    Month = 12;
                }

                Day = DateTime.Now.Day;
                txtStartDate.Text = Year1.ToString() + "-" + Month.ToString() + "-01";
                txtEndDate.Text = Year.ToString() + "-" + DMonth.ToString() + "-01";
            }

            _strEndDate = txtEndDate.Text.ToString();
            _strStartDate = txtStartDate.Text.ToString();
            if (_strStartDate != "" && _strEndDate != "")
            {
                if (Request.Form["butSelectAll"] == "查看全部")
                {

                    string strSql = @"select  accountid_ps,companyname_ps,usercode_ps,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE ,convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE
                                  ,convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as bidprice,convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as bakeprice,convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS Nolimtprice,
                                  convert(numeric(20,2),SUM(case when GoodsState=3 then inflownum*TradePrice else 0 end)) AS GMPprice,convert(numeric(20,2),SUM(case when GoodsState=4 then inflownum*TradePrice else 0 end)) AS KeyPrice,
                                    from tra_GoodsId where  {0}  group by accountid_ps,companyname_ps,usercode_ps  Order By DHJE desc,accountid_ps ";
                    string _strtempWhere = fctConditions();
                    strSql = String.Format(strSql, _strtempWhere);
                    Db db1 = new Db();
                    System.Data.IDataReader dr;
                    dr = db1.DataReader(strSql);
                    GridView1.DataSource = dr;
                    GridView1.DataBind();
                    dr.Close();
                    dr.Dispose();
                    db1.Close();
                }
                else
                {
                    showGridView();
                }
            }
        }
    }
    protected void Button5_Click(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// 数据绑定
    /// </summary>
    public void showGridView()
    {

        string strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "tra_GoodsId_200708";                                               //要查询的表明
        dbPage.SelectFieldGroup = "accountid_PS,CompanyName_PS,UserCode_PS,DealStatus";
        dbPage.Key = "accountid_PS";                                               //表的主键    
        dbPage.Where = strConditions;                                           //查询条件    
        dbPage.SelectField = "accountid_PS,CompanyName_PS,UserCode_PS,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE ,convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE,convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as bidprice,convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as bakeprice,convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS Nolimtprice,convert(numeric(20,2),SUM(case when GoodsState=3 then inflownum*TradePrice else 0 end)) AS GMPprice,convert(numeric(20,2),SUM(case when GoodsState=4 then inflownum*TradePrice else 0 end)) AS KeyPrice,case DealStatus when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到到期未送' end as DealStatus";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 30;                                                    //没有显示记录条数   
        dbPage.OrderBy = "DHJE,accountid_ps";                  //排序字段
        dbPage.OrderByIsDesc = true;
        dbPage.DGJE = "convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE";
        dbPage.DHJE = "convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE";
        System.Data.IDataReader dr = dbPage.ExecuteReaderGroup(60);
        GridView1.DataSource = dr;
        GridView1.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键



    }
    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <returns></returns>
    public string fctConditions()
    {
        string _strTemp = " DealStatus >=0 and DealStatus<>3 and", CompanyName = "", _UserCode, _strAreaIdForm;

        //医院范围
        if (_strUserType == "3")
        {
            _strTemp += "  AccountId_YY=" + _strAccountId_YY + " and";
        }
        else
        {
            //
            _strAreaIdForm = SysFun.ToTrim(Request.Form["txtAreaId"]);
            if (_strAreaIdForm != "" && _strAreaIdForm != "530000")
            {
                _AreaId = _strAreaIdForm;
            }
            _strTemp += SysFun.AreaIdWhere(_AreaId);
        }

        //时间范围
        _strEndDate = txtEndDate.Text.ToString();
        _strStartDate = txtStartDate.Text.ToString();
        if (_strEndDate != "" && _strStartDate != "")
        {
            _strTemp += " isnull(hospitalinflowdate,'3000-12-30') >='" + _strStartDate + "' and isnull(hospitalinflowdate,'1900-01-01') <='" + _strEndDate + "' and";
        }

        //企业注册号
        _UserCode = txtUserCode.Text.ToString().Trim();
        if (_UserCode != "")
        {
            _strTemp += " UserCode_PS like '%" + _UserCode + "%' and";
        }

        //企业名称
        CompanyName = txtAttorneyName.Text.ToString().Trim();
        if (CompanyName != "")
        {
            _strTemp += " CompanyName_PS like '%" + CompanyName + "%' and";
        }

        if (dealDrop.SelectedValue != "")
        {
            if (dealDrop.SelectedValue == "0")
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and buystatus=2 and";
            }
            else
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and";
            }
        }

        if (_strTemp != "")
        {
            _strTemp = "  " + _strTemp.Substring(0, _strTemp.Length - 3);
        }
        return _strTemp;
    }
    protected void ToEcxul_Click(object sender, EventArgs e)//导出
    {
        //0 原中标商品 1 自行采购  2  22种降价 3 人血蛋白 4 重点监控 默认为‘0’
        Db db = new Db();
        System.Data.IDataReader dr;

        string _strSql = "Select CompanyName_PS as 企业名称,UserCode_PS as 企业名注册号,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as '订货金额（元）' ,convert(numeric(20,2),sum(inflownum*TradePrice)) as '到货金额（元）',convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as '原中标（元）',convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as '自行采购（元）',convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS '22种降价（元）',convert(numeric(20,2),SUM(case when GoodsState=3 then inflownum*TradePrice else 0 end)) AS 血液制品,convert(numeric(20,2),SUM(case when GoodsState=4 then inflownum*TradePrice else 0 end)) AS 重点监控,case DealStatus when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到到期未送' end as 采购状态  From tra_GoodsId Where   " + fctConditions() + "  Group By accountid_PS,CompanyName_PS,UserCode_PS,DealStatus Order By '订货金额（元）' Desc,accountid_ps Desc";

        dr = db.DataReader(_strSql);
        this.GridView2.DataSource = dr;
        this.GridView2.DataBind();
        db.Close();
        dr.Close();
        dr.Dispose();
        SysFun.WriteToExcel(GridView2, this.Page, "交易记录[按配送企业查询].xls");


    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！
    }
    #region TraDes 成员

    public string Name
    {
        get { return "按配送企业查询"; }
    }

    public string Describe
    {
        get { return ""; }
    }

    public string ParentName
    {
        get { return "交易查询"; }
    }

    public System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> UseAccountType
    {
        get
        {
            System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumHospitale);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumAttorney);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSupervise);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSuperviseChildCheck);
            return _AccountType;
        }
    }
    #endregion

    protected void BuildReport_Click(object sender, EventArgs e)
    {
        try
        {
            this.BuildReport2.Enabled = false;
            Db db = new Db();
            DataTable dt1 = db.DataTable(sqlwhere("1"));
            DataTable dt2 = db.DataTable(sqlwhere("2"));
            DataTable dt0 = db.DataTable(sqlwhere("0"));
            DataTable dt4 = db.DataTable(sqlwhere("4"));
            DataTable dt5 = db.DataTable(sqlwhere("5"));
            DataTable dt = new DataTable();
            dt.Columns.Add("地市名");
            dt.Columns.Add("送货中(金额)");
            dt.Columns.Add("送货中(企业数)");
            dt.Columns.Add("已入库(金额)");
            dt.Columns.Add("已入库(企业数)");
            dt.Columns.Add("未确认送货(金额)");
            dt.Columns.Add("未确认送货(企业数)");
            dt.Columns.Add("无法配送(金额)");
            dt.Columns.Add("无法配送(企业数)");
            dt.Columns.Add("到期未配送(金额)");
            dt.Columns.Add("到期未配送(企业数)");
            for (int i = 0; i < 18; i++)
            {
                dt.Rows.Add(1);
                dt.Rows[i][0] = dt1.Rows[i][0];
                dt.Rows[i][1] = dt1.Rows[i][2];
                dt.Rows[i][2] = dt1.Rows[i][1];
                dt.Rows[i][3] = dt2.Rows[i][2];
                dt.Rows[i][4] = dt2.Rows[i][1];
                dt.Rows[i][5] = dt0.Rows[i][2];
                dt.Rows[i][6] = dt0.Rows[i][1];
                dt.Rows[i][7] = dt4.Rows[i][2];
                dt.Rows[i][8] = dt4.Rows[i][1];
                dt.Rows[i][9] = dt5.Rows[i][2];
                dt.Rows[i][10] = dt5.Rows[i][1];
            }

            this.GridView2.DataSource = dt;
            this.GridView2.DataBind();
            db.Close();
            dt = null;
            dt1 = null;
            dt2 = null;
            dt0 = null;
            dt4 = null;
            dt5 = null;
            SysFun.WriteToExcel(GridView2, this.Page, "表Ⅱ各地市配送情况.xls");
            
        }
        catch (System.Exception )
        {
        	
        }
        finally
        {
            this.BuildReport2.Enabled = true;
        }
       

    }

   protected string sqlwhere (string dealstatus)
   {
       string _strSql = " select  city_henan.areaname as 城市 ,count(a.areaname) as 企业数,sum(DGJE) as 订购金额,sum(DHJE) as 到款金额 from (select  DealStatus,areaname,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE,convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE   from  tra_GoodsId_200708 where dealstatus=" + dealstatus;
       _strEndDate = txtEndDate.Text.ToString();
       _strStartDate = txtStartDate.Text.ToString();
       if (_strEndDate != "" && _strStartDate != "")
       {
           _strSql += " and isnull(hospitalinflowdate,'3000-12-30') >='" + _strStartDate + "' and isnull(hospitalinflowdate,'1900-01-01') <='" + _strEndDate + "' ";
       }

       _strSql += "group by accountid_PS,CompanyName_PS,UserCode_PS,DealStatus,areaname  )a  right join city_henan on city_henan.areaname=a.areaname group  by city_henan.areaname, city_henan.areaid,DealStatus  order by city_henan.areaid";
       return _strSql;

   }
    protected void BuildReport1_Click(object sender, EventArgs e)
    {       
        try
        {
            this.BuildReport1.Enabled = false;
            _strEndDate = txtEndDate.Text.ToString();
            _strStartDate = txtStartDate.Text.ToString();
            string _strSql = "select case DealStatus when '1' then '送货中' when '2' then'已入库' when '4' then '无法配送' when '5' then '到期未配送' when '0' then '未确认送货'  end  as  状态,count(1)  as  企业家数,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as 金额  from tra_GoodsId_200708 where DealStatus<>3 and  DealStatus <6  and  isnull(hospitalinflowdate,'3000-12-30') >='" + _strStartDate + "' and isnull(hospitalinflowdate,'1900-01-01') <='" + _strEndDate + "'  group by DealStatus  ";
            Db db = new Db();
            DataTable dt = db.DataTable(_strSql);
            this.GridView2.DataSource = dt;
            this.GridView2.DataBind();
            db.Close();
            dt = null;
            SysFun.WriteToExcel(GridView2, this.Page, "表Ⅰ全省配送情况.xls");

            
        }
        catch (System.Exception )
        {
        	
        }
        finally
        {
            this.BuildReport1.Enabled = true;
        }
        
    }
}
